package com.example.mvvm.until;

import android.app.Activity;
import android.util.Log;

import androidx.fragment.app.FragmentActivity;

import com.example.mvvm.base.BaseActivity;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import static android.content.Context.ACTIVITY_SERVICE;


/**
 * 管理Acitivy,退出时，退到登录时候销毁已存在的
 */

public class ActivityManager {
    private static ActivityManager instance = new ActivityManager();
    private static Map<Class, WeakReference<BaseActivity>> hashMap = new HashMap<>();

    private ActivityManager() {

    }

    public void removeActivity(Class mClass) {
        WeakReference<BaseActivity> baseActivityWeakReference = hashMap.get(mClass);
        if (baseActivityWeakReference != null) {
            baseActivityWeakReference.clear();
            hashMap.remove(mClass);
        }

    }

    public static ActivityManager getInstance() {
        return instance;
    }

    /**
     * 每一个Activity 在 onCreate 方法的时候，可以装入当前this
     *
     * @param activity
     */
    public void addActivity(Class mClass, BaseActivity activity) {
        try {
            hashMap.put(mClass, new WeakReference<>(activity));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public <T> BaseActivity getActivity(Class<T> mClass) {
        try {
            return hashMap.get(mClass).get();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 调用此方法用于销毁所有的Activity，然后我们在调用此方法之前，调到登录的Activity
     */
    public void exit() {
        try {
            for (Map.Entry<Class, WeakReference<BaseActivity>> activityEntry : hashMap.entrySet()) {
                BaseActivity activity = activityEntry.getValue().get();
                if (activity != null)
                    activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断APP是否进入前台
     */
    public boolean isRunningForeground(FragmentActivity context) {
        android.app.ActivityManager activityManager = (android.app.ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<android.app.ActivityManager.RunningAppProcessInfo> appProcessInfos = activityManager.getRunningAppProcesses();
        if (appProcessInfos == null) {
            return false;
        }
        // 枚举进程
        for (android.app.ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfos) {
            if (appProcessInfo.importance == android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                if (appProcessInfo.processName.equals(context.getApplicationInfo().processName)) {
                    Log.i("myBack", "true");
                    return true;
                }
            }
        }
        Log.i("myBack", "false");
        return false;
    }
}
